package com.pai4j.common.service.messagequeue.producer;

import com.pai4j.common.enums.messagequeue.MessageBroadChannelEnum;
import com.pai4j.common.enums.messagequeue.MessageQueueEnum;
import com.pai4j.common.exception.BusinessException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
/**
 *  消息队列生产者
 *
 * @author: CYM-pai
 * @date: 2025/04/29 21:13
 **/
@RefreshScope
@Service
public class MessageQueueProducer<T, P> {

    @Resource
    private RocketMessageQueueSender<T, P> rocketMessageQueueSender;

    @Resource
    private RedisMessageQueueSender<T, P> redisMessageQueueSender;

    /**
     * 消息队列开关配置，支持：rocketmq、redis、kafka等
     */
    @Value("${message-queue.used:redis}")
    private String messageQueueUsed;

    /**
     * 普通队列消息发送
     *
     * @param queue
     * @param message
     */
    public void send(MessageQueueEnum queue, T message) {

        this.getSender().send(queue, message);
    }

    /**
     * 优先级队列消息发送
     *
     * @param queue
     * @param message
     * @param priority
     */
    public void prioritySend(MessageQueueEnum queue, T message, P priority) {

        this.getSender().prioritySend(queue, message, priority);
    }

    /**
     * 广播消息发送
     *
     * @param channel
     * @param message
     */
    public void broadSend(MessageBroadChannelEnum channel, T message) {

        this.getSender().broadSend(channel, message);
    }

    /**
     * 根据配置的消息队列类型获取相应的发送器
     *
     * 此方法通过检查配置文件中指定的消息队列类型，来决定实例化并返回哪种消息队列发送器
     * 目前支持两种消息队列：RocketMQ和Redis当配置的消息队列类型不在这两种之内时，
     * 方法会抛出业务异常
     *
     * @return AbstractMessageQueueSender<T, P> 根据配置返回对应的消息队列发送器实例
     * @throws BusinessException 如果配置的消息队列类型不受支持，则抛出此异常
     */
    private AbstractMessageQueueSender<T, P> getSender() {
        if (messageQueueUsed.equals("rocketmq")) {
            return rocketMessageQueueSender;
        } else if (messageQueueUsed.equals("redis")) {
            return redisMessageQueueSender;
        }
        throw new BusinessException("不支持的队列类型！");
    }
}
